package com.example.demo11.dao;

import com.example.demo11.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@Repository
public class RoleDaoImpl implements RoleDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int add(Role user) {
        return jdbcTemplate.update("INSERT INTO role (id,name,password,email,description) VALUE(?,?,?,?,?)", user.getId(), user.getName(), user.getPassword(), user.getEmail(),user.getDescription());
    }

    @Override
    public int update(Role user) {
        return jdbcTemplate.update("UPDATE role SET name = ?, password = ?, email = ?, description = ? WHERE id = ?",user.getName(), user.getPassword(), user.getEmail(),user.getDescription(),user.getId());
    }

    @Override
    public List<Map<String, Object>> findByName(String name) {

        List<Map<String, Object>> user = jdbcTemplate.queryForList("SELECT * FROM role WHERE name like ?", new Object[]{"%" + name + "%"});
        if (user != null && user.size() > 0)
            return user;
        else
            return null;
    }

    @Override
    public Role findById(Integer id) {
        List<Role> user = jdbcTemplate.query("SELECT * FROM role WHERE id = ?", new Object[]{id}, new BeanPropertyRowMapper<>(Role.class));
        if (user != null && user.size() > 0)
            return user.get(0);
        else
            return null;
    }

    @Override
    public int delete(Integer id) {
        return jdbcTemplate.update("DELETE FROM role where id = ?", id);
    }

    @Override
    public List<Map<String, Object>> findRoleByUserName(String name) {
        return null;
    }

    @Override
    public List<Map<String, Object>> findUserByRoleName(String name) {
        List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT user.id,user.name,user.password,user.email FROM user_role,user WHERE user_role.role_id = (SELECT id FROM role WHERE role.role = ?) AND user.id = user_role.user_id;", new Object[]{name});
        if (list != null && list.size() > 0)
            return list;
        else
            return null;
    }

    @Override
    public List<Map<String, Object>> findRoleByUserId(Integer id) {
        return null;
    }

    @Override
    public List<Map<String, Object>> findUserByRoleId(Integer id) {
        return null;
    }

    @Override
    public List<Map<String, Object>> findAll(Integer page) {
        int index = (page - 1) * 5;
        List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT * FROM role LIMIT ?,5;", new Object[]{index});
        if (list != null && list.size() > 0)
            return list;
        else
            return null;
    }
}
